<template>
  <div class="maintenance-management-container">
    <div class="maintenance-management-header">
      <div class="header-actions">
        <el-button type="primary" plain size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回首页
        </el-button>
      </div>
      <h1>景点维修管理</h1>
      <p>管理青岛自然保护区景点维修信息</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧地图区域 -->
      <el-col :span="16">
        <el-card class="map-card">
          <div id="scenicMapView" class="map-container"></div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 景区选择 -->
        <el-card class="area-select-card">
          <template #header>
            <div class="card-header">
              <span>景点选择</span>
            </div>
          </template>

          <div class="area-tabs">
            <el-tabs v-model="activeArea" @tab-click="handleAreaChange">
              <el-tab-pane label="胶南灵山岛景点" name="erdihu"></el-tab-pane>
            <el-tab-pane label="大公岛景点" name="yunmen"></el-tab-pane>
            <el-tab-pane label="大泽山景点" name="bailang"></el-tab-pane>
            <el-tab-pane label="崂山景点" name="xiashan"></el-tab-pane>
            <el-tab-pane label="胶州艾山景点" name="binhai"></el-tab-pane>
            <el-tab-pane label="马山景点" name="mihe"></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 维修状态筛选 -->
        <el-card class="filter-card">
          <template #header>
            <div class="card-header">
              <span>维修状态筛选</span>
            </div>
          </template>

          <div class="filter-options">
            <el-radio-group v-model="selectedStatus" @change="handleStatusFilterChange">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="pending">待处理</el-radio-button>
              <el-radio-button label="in-progress">处理中</el-radio-button>
              <el-radio-button label="resolved">已解决</el-radio-button>
            </el-radio-group>
          </div>
        </el-card>

        <!-- 维修报告列表 -->
        <el-card class="maintenance-list-card">
          <template #header>
            <div class="card-header">
              <span>维修报告列表</span>
              <el-input
                v-model="searchQuery"
                placeholder="搜索景点名称"
                prefix-icon="Search"
                clearable
                @input="handleSearch"
                size="small"
                style="width: 200px"
              />
            </div>
          </template>

          <div v-loading="loading">
            <div v-if="maintenanceReports.length > 0">
              <el-collapse accordion>
                <el-collapse-item
                  v-for="(report, index) in maintenanceReports"
                  :key="index"
                  :name="index"
                >
                  <template #title>
                    <div class="report-title">
                      <span>{{ report.scenicName }} - {{ report.title }}</span>
                      <el-tag :type="getStatusTagType(report.status)" size="small">
                        {{ getStatusText(report.status) }}
                      </el-tag>
                    </div>
                  </template>
                  <div class="report-content">
                    <p><strong>上报者:</strong> {{ report.reporter }}</p>
                    <p><strong>上报时间:</strong> {{ formatDate(report.reportDate) }}</p>
                    <p><strong>严重程度:</strong> {{ getSeverityText(report.severity) }}</p>
                    <p><strong>问题描述:</strong> {{ report.description }}</p>

                    <div v-if="report.photoBase64" class="report-image">
                      <el-image
                        style="width: 100%; max-height: 200px"
                        :src="report.photoBase64"
                        fit="contain"
                        :preview-src-list="[report.photoBase64]"
                      ></el-image>
                    </div>

                    <div class="report-comments" v-if="report.comments && report.comments.length > 0">
                      <h4>处理记录:</h4>
                      <div
                        v-for="(comment, cIndex) in report.comments"
                        :key="cIndex"
                        class="comment-item"
                      >
                        <p class="comment-header">
                          <span>{{ comment.user }}</span>
                          <span>{{ formatDate(comment.date) }}</span>
                        </p>
                        <p class="comment-text">{{ comment.text }}</p>
                      </div>
                    </div>

                    <div class="report-actions">
                      <el-button
                        v-if="report.status !== 'resolved'"
                        type="primary"
                        size="small"
                        @click="updateReportStatus(report, 'in-progress')"
                      >
                        标记为处理中
                      </el-button>
                      <el-button
                        v-if="report.status !== 'resolved'"
                        type="success"
                        size="small"
                        @click="updateReportStatus(report, 'resolved')"
                      >
                        标记为已解决
                      </el-button>
                      <el-button
                        type="info"
                        size="small"
                        @click="openCommentForm(report)"
                      >
                        添加处理记录
                      </el-button>
                      <el-button
                        type="warning"
                        size="small"
                        @click="locateOnMap(report)"
                      >
                        在地图上定位
                      </el-button>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
            <el-empty v-else description="暂无维修报告数据"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 添加处理记录对话框 -->
  <el-dialog
    v-model="showCommentDialog"
    title="添加处理记录"
    width="500px"
  >
    <el-form
      ref="commentFormRef"
      :model="commentForm"
      :rules="commentRules"
      label-width="100px"
    >
      <el-form-item label="处理记录" prop="text">
        <el-input
          v-model="commentForm.text"
          type="textarea"
          :rows="4"
          placeholder="请输入处理记录内容"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
declare global {
  interface Window {
    _tempFeatures: __esri.Graphic[]
  }
}
import { ref, onMounted, reactive, computed } from 'vue'
import { Back, Search } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import { gaodeLayer } from '@/utils/GaoDeBaseLayer'

// 维修报告接口
interface MaintenanceReport {
  id: string
  title: string
  description: string
  severity: string
  photoBase64: string
  reportDate: string
  status: string
  reporter: string
  comments: { user: string; text: string; date: string }[]
  // 额外添加的字段，用于显示
  scenicName: string
  OBJECTID: number
  featureIndex: number
}

// 用户存储和路由
const userStore = useUserStore()
const router = useRouter()

// 地图和图层
let view: __esri.MapView
let featureLayers: __esri.FeatureLayer[] = []

// 状态变量
const loading = ref(true)
const searchQuery = ref('')
const allFeatures = ref<any[]>([])
const selectedStatus = ref('all')
const showCommentDialog = ref(false)
const currentReport = ref<MaintenanceReport | null>(null)
const commentFormRef = ref<FormInstance>()

// 当前选中的景区
const activeArea = ref('erdihu') // 默认胶南灵山岛保护区

// 各个景区的中心坐标
const areaCenters = {
  erdihu: [120.179558,35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415,35.967122], // 大公岛坐标
  bailang: [120.022251,37.00615], // 大泽山坐标
  xiashan: [120.605305,36.198964], // 崂山坐标
  binhai: [119.93718,36.121442], // 胶州艾山坐标
  mihe: [120.651138,36.340289] // 马山坐标
}

// 评论表单
const commentForm = reactive({
  text: ''
})

// 评论表单验证规则
const commentRules = reactive<FormRules>({
  text: [
    { required: true, message: '请输入处理记录内容', trigger: 'blur' },
    { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
  ]
})

// 景区名称映射
const areaNameMap = {
  erdihu: '胶南灵山岛保护区',
  yunmen: '大公岛保护区',
  bailang: '大泽山保护区',
  xiashan: '崂山保护区',
  binhai: '胶州艾山保护区',
  mihe: '马山保护区'
}

// 计算属性：维修报告列表
const maintenanceReports = computed(() => {
  // 从所有要素中提取维修报告
  const reports: MaintenanceReport[] = []

  allFeatures.value.forEach((feature, featureIndex) => {
    // 根据当前选中的景区筛选
    const currentAreaName = areaNameMap[activeArea.value as keyof typeof areaNameMap]
    if (feature.attributes.OwnerScenic !== currentAreaName) {
      return
    }

    if (feature.attributes.MaintanceDataJson) {
      try {
        const maintanceData = JSON.parse(feature.attributes.MaintanceDataJson)
        if (Array.isArray(maintanceData) && maintanceData.length > 0) {
          maintanceData.forEach((report: any) => {
            // 根据状态筛选
            if (selectedStatus.value === 'all' || report.status === selectedStatus.value) {
              // 根据搜索条件筛选
              if (!searchQuery.value || feature.attributes.ScenicName.includes(searchQuery.value)) {
                reports.push({
                  ...report,
                  scenicName: feature.attributes.ScenicName,
                  OBJECTID: feature.attributes.OBJECTID,
                  featureIndex
                })
              }
            }
          })
        }
      } catch (e) {
        console.error('解析维修数据失败', e)
      }
    }
  })

  // 按上报时间排序，最新的在前面
  return reports.sort((a, b) => new Date(b.reportDate).getTime() - new Date(a.reportDate).getTime())
})

// 查询景点数据
const queryFeatures = async () => {
  if (featureLayers.length === 0) return

  loading.value = true
  try {
    const layer = featureLayers[0]

    // 创建查询
    const query = layer.createQuery()
    query.where = '1=1' // 查询所有数据
    query.outFields = ['*']

    try {
      // 执行查询
      const result = await layer.queryFeatures(query)

      // 为每个要素添加图层信息
      result.features.forEach((feature, index) => {
        // 添加图层类型标识
        if (feature.attributes) {
          feature.attributes._layerType = 'scenic'
          feature.attributes._layerIndex = 0
          feature.attributes._index = index
        }
      })

      // 存储原始的ESRI要素对象到非响应式变量中
      window._tempFeatures = result.features

      // 将要素数据存储到响应式变量中
      allFeatures.value = result.features.map((feature, index) => ({
        _index: index,
        attributes: { ...feature.attributes },
        geometryInfo: feature.geometry
          ? {
              x: feature.geometry.type === 'point' ? (feature.geometry as __esri.Point).x : null,
              y: feature.geometry.type === 'point' ? (feature.geometry as __esri.Point).y : null,
              type: feature.geometry.type,
            }
          : null,
      }))
    } catch (layerError) {
      console.error('查询景点图层数据失败', layerError)
    }
  } catch (error) {
    console.error('查询景点数据失败', error)
    allFeatures.value = []
  } finally {
    loading.value = false
  }
}

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: 'streets-vector',
  })

  // 创建地图视图
  view = new MapView({
    container: 'scenicMapView',
    map: map,
    center: areaCenters[activeArea.value as keyof typeof areaCenters], // 根据当前选中的景区设置中心点
    zoom: 13,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建景点要素图层
  const featureLayer = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'unique-value',
      field: 'ScenicType',
      uniqueValueInfos: [
        {
          value: '自然景观',
          symbol: {
            type: 'simple-marker',
            color: [34, 139, 34],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '人文景观',
          symbol: {
            type: 'simple-marker',
            color: [30, 144, 255],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '历史遗迹',
          symbol: {
            type: 'simple-marker',
            color: [255, 140, 0],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '休闲娱乐',
          symbol: {
            type: 'simple-marker',
            color: [255, 20, 147],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '观景台',
          symbol: {
            type: 'simple-marker',
            color: [128, 128, 128],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        }
      ]
    },
    labelingInfo: [
      {
        labelExpression: '$feature.ScenicName',
        symbol: {
          type: 'text',
          color: 'black',
          font: {
            size: 10,
            weight: 'bold'
          }
        },
        minScale: 50000
      }
    ]
  })

  // 将图层添加到地图
  map.add(featureLayer)

  // 存储图层用于查询
  featureLayers = [featureLayer]

  // 加载要素数据
  await queryFeatures()
}


// 处理景区切换
const handleAreaChange = () => {
  // 将地图中心移动到选中的景区
  view?.goTo({
    center: areaCenters[activeArea.value as keyof typeof areaCenters],
    zoom: 13,
  })
}

// 处理状态筛选变化
const handleStatusFilterChange = () => {
  // 状态筛选变化时不需要重新查询数据，只需要重新计算 maintenanceReports
}

// 处理搜索
const handleSearch = () => {
  // 搜索条件变化时不需要重新查询数据，只需要重新计算 maintenanceReports
}

// 在地图上高亮显示要素
const highlightFeatureOnMap = (feature: any) => {
  if (!feature || !feature.geometry) return

  // 清除之前的高亮
  view?.graphics.removeAll()

  // 创建高亮符号
  const highlightSymbol = new SimpleMarkerSymbol({
    color: [255, 255, 255, 0.8],
    size: 16,
    outline: {
      color: [0, 122, 194],
      width: 3,
    },
  })

  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: feature.geometry,
    symbol: highlightSymbol,
  })

  // 添加到地图
  view?.graphics.add(highlightGraphic)

  // 将视图中心移动到要素位置
  view?.goTo({
    target: feature.geometry,
    zoom: 15,
  })
}

// 在地图上定位
const locateOnMap = (report: MaintenanceReport) => {
  // 从非响应式存储中获取原始要素
  const originalFeature = window._tempFeatures?.[report.featureIndex]
  if (originalFeature) {
    highlightFeatureOnMap(originalFeature)
  }
}

// 更新报告状态
const updateReportStatus = async (report: MaintenanceReport, newStatus: string) => {
  try {
    // 从非响应式存储中获取原始要素
    const feature = window._tempFeatures?.[report.featureIndex]
    if (!feature) {
      ElMessage.error('无法获取保护区信息')
      return
    }

    // 获取现有的维修数据
    let maintenanceData = []
    if (feature.attributes.MaintanceDataJson) {
      try {
        maintenanceData = JSON.parse(feature.attributes.MaintanceDataJson)
      } catch (e) {
        console.error('解析现有维修数据失败', e)
        maintenanceData = []
      }
    }

    // 更新状态
    const updatedData = maintenanceData.map((item: any) => {
      if (item.id === report.id) {
        return {
          ...item,
          status: newStatus,
          comments: [
            ...item.comments,
            {
              user: userStore.currentUser?.username || '管理员',
              text: `将状态更新为"${getStatusText(newStatus)}"`,
              date: new Date().toISOString()
            }
          ]
        }
      }
      return item
    })

    // 更新要素
    const updateFeature = new Graphic({
      attributes: {
        OBJECTID: feature.attributes.OBJECTID,
        MaintanceDataJson: JSON.stringify(updatedData)
      }
    })

    // 根据要素的图层索引确定使用哪个图层
    const layerIndex = feature.attributes._layerIndex || 0
    const targetLayer = featureLayers[layerIndex]

    const result = await targetLayer.applyEdits({
      updateFeatures: [updateFeature]
    })

    if (result.updateFeatureResults.length > 0) {
      ElMessage.success('维修状态已更新')
      await queryFeatures()
    } else {
      ElMessage.error('更新维修状态失败')
    }
  } catch (error) {
    console.error('更新维修状态失败', error)
    ElMessage.error('更新维修状态失败')
  }
}

// 打开添加处理记录表单
const openCommentForm = (report: MaintenanceReport) => {
  currentReport.value = report
  commentForm.text = ''
  showCommentDialog.value = true
}

// 提交处理记录
const submitComment = async () => {
  if (!commentFormRef.value || !currentReport.value) return

  await commentFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请完善表单信息')
      return
    }

    try {
      // 从非响应式存储中获取原始要素
      const feature = window._tempFeatures?.[currentReport.value!.featureIndex]
      if (!feature) {
        ElMessage.error('无法获取保护区信息')
        return
      }

      // 获取现有的维修数据
      let maintenanceData = []
      if (feature.attributes.MaintanceDataJson) {
        try {
          maintenanceData = JSON.parse(feature.attributes.MaintanceDataJson)
        } catch (e) {
          console.error('解析现有维修数据失败', e)
          maintenanceData = []
        }
      }

      // 添加处理记录
      const updatedData = maintenanceData.map((item: any) => {
        if (item.id === currentReport.value?.id) {
          return {
            ...item,
            comments: [
              ...item.comments,
              {
                user: userStore.currentUser?.username || '管理员',
                text: commentForm.text,
                date: new Date().toISOString()
              }
            ]
          }
        }
        return item
      })

      // 更新要素
      const updateFeature = new Graphic({
        attributes: {
          OBJECTID: feature.attributes.OBJECTID,
          MaintanceDataJson: JSON.stringify(updatedData)
        }
      })

      // 根据要素的图层索引确定使用哪个图层
      const layerIndex = feature.attributes._layerIndex || 0
      const targetLayer = featureLayers[layerIndex]

      const result = await targetLayer.applyEdits({
        updateFeatures: [updateFeature]
      })

      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('处理记录已添加')
        showCommentDialog.value = false
        await queryFeatures()
      } else {
        ElMessage.error('添加处理记录失败')
      }
    } catch (error) {
      console.error('添加处理记录失败', error)
      ElMessage.error('添加处理记录失败')
    }
  })
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'in-progress':
      return 'primary'
    case 'resolved':
      return 'success'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'in-progress':
      return '处理中'
    case 'resolved':
      return '已解决'
    default:
      return '未知'
  }
}

// 获取严重程度文本
const getSeverityText = (severity: string) => {
  switch (severity) {
    case 'minor':
      return '轻微'
    case 'moderate':
      return '中等'
    case 'severe':
      return '严重'
    default:
      return '未知'
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return dateString
  }
}

// 返回首页
const goBack = () => {
  router.push('/')
}


// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})
</script>

<style scoped lang="scss">
.maintenance-management-container {
  padding: 20px;
}

.maintenance-management-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left: 4px solid #409eff;
}

.header-actions {
  margin-bottom: 15px;
}

.maintenance-management-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.maintenance-management-header p {
  color: #606266;
  font-size: 14px;
}

.map-container {
  height: 400px;
  width: 100%;
  position: relative;
}

.map-card,
.area-select-card,
.filter-card,
.maintenance-list-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-options {
  padding: 10px 0;
}

.report-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.report-content {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.report-content p {
  margin-bottom: 8px;
}

.report-image {
  margin: 10px 0;
}

.report-comments {
  margin-top: 15px;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
}

.report-comments h4 {
  margin-bottom: 10px;
  color: #303133;
}

.comment-item {
  background-color: #fff;
  padding: 8px;
  border-radius: 4px;
  margin-bottom: 8px;
  border-left: 3px solid #409eff;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 12px;
  margin-bottom: 5px;
}

.comment-text {
  color: #303133;
}

.report-actions {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .maintenance-management-container {
    padding: 10px;
  }

  .map-container {
    height: 300px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .report-actions {
    flex-direction: column;
  }
}
</style>
